<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="crud-group">
      <!-- 搜索 -->
      <el-input
        v-model="query.taskCode"
        clearable
        placeholder="请输入导入批次"
        style="width: 140px"
      />
      <el-input
        v-model="query.taskName"
        clearable
        placeholder="请输入任务名"
        style="width: 140px"
      />
      <el-select
        v-model="query.taskStatus"
        placeholder="请选择导入状态"
        style="width: 150px"
      >
        <el-option
          v-for="item in taskStatusList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <rrOperation :crud="crud" />
      <el-button
        icon="el-icon-plus"
        size="mini"
        type="primary"
        @click="() => { crud.toAdd() }"
      >
        创建任务
      </el-button>
      <el-button
        :disabled="dynamicSuspendButton(crud.selections)"
        type="danger"
        icon="el-icon-video-pause"
        size="mini"
        @click="suspend(crud.selections)"
      >暂停
      </el-button>
      <el-button
        :disabled="dynamicRestartButton(crud.selections)"
        type="primary"
        icon="el-icon-video-play"
        size="mini"
        @click="restart(crud.selections)"
      >继续
      </el-button>
      <el-button
        :disabled="dynamicAbolishButton(crud.selections)"
        type="danger"
        icon="el-icon-switch-button"
        size="mini"
        @click="abolish(crud.selections)"
      >中止
      </el-button>
      <el-button
        type="success"
        size="mini"
        icon="el-icon-search"
        @click="toShowAllDetail()"
      >导入列表
      </el-button>
    </div>
    <!--表格渲染-->
    <el-table
      ref="table"
      v-loading="crud.loading"
      :data="crud.data"
      border
      @select="crud.selectChange"
      @select-all="crud.selectAllChange"
      @selection-change="crud.selectionChangeHandler"
    >
      <el-table-column
        type="selection"
        width="40"
      />
      <el-table-column
        fixed
        label="导入批次"
        prop="taskCode"
        width="130"
      />
      <el-table-column
        label="任务名称"
        prop="taskName"
        width="180"
      />
      <el-table-column
        label="同步模式"
        prop="transferModelString"
        width="400"
      />
      <el-table-column
        label="导入路径"
        prop="filePath"
        width="220"
      />
      <el-table-column
        label="表名称"
        prop="libraryTableName"
        width="100px"
      >
        <template slot-scope="scope">
          <a
            style="color: dodgerblue"
            @click="libraryTableopen(scope.row.taskCode)"
          >查看表名称</a>
        </template>
      </el-table-column>
      <el-table-column
        label="导入状态"
        prop="taskStatusName"
      />
      <el-table-column
        label="导入进度"
        width="300px"
      >
        <template slot-scope="scope">
          <el-tag type="info">总数：{{ scope.row.importTotal }}</el-tag>
          <el-tag
            v-if="scope.row.taskStatus !== 'build'"
            type="success"
            style="margin: 0px 5px"
          >成功数量:
            {{ scope.row.importSuccess }}
          </el-tag>
          <el-tag
            v-if="scope.row.taskStatus !== 'build'"
            type="danger"
          >失败数量: {{ scope.row.importFail }}</el-tag>
          <el-tag
            v-if="scope.row.taskStatus === 'build'"
            type="success"
            style="margin: 0px 5px"
          >构建数量:
            {{ scope.row.buildCount }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="开始时间"
        prop="startTimeString"
        width="180"
      />
      <el-table-column
        label="结束时间"
        prop="endTimeString"
        width="180"
      />
      <el-table-column
        label="耗时"
        prop="timeConsuming"
        width="120"
      />
      <el-table-column
        fixed="right"
        label="操作"
        width="200"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="toShowDetail(scope.row.taskCode)"
          >查看</el-button>
          <el-button
            type="text"
            :disabled="scope.row.taskStatus !== 'running'"
            @click="continueRun(scope.row.id)"
          >
            重新加载
          </el-button>
          <el-button
            type="text"
            @click="toShowErrorMessage(scope.row)"
          >错误信息</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="float: right">
      <!--分页组件-->
      <pagination />
    </div>

    <el-dialog
      :close-on-click-modal="false"
      title="开发数据导入"
      width="40%"
      append-to-body
      :visible="crud.status.add > 0"
      @close="crud.cancelCU"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        :inline="true"
        label-width="150px"
      >
        <el-row>
          <el-form-item
            label="数据文件路径"
            prop="filePath"
          >
            <el-input
              v-model="form.filePath"
              clearable
              size="small"
              placeholder="请输入数据文件时间标识"
            >
              <template slot="prepend">
                backup/dmpro/dev-data/
              </template>
            </el-input>
          </el-form-item>
        </el-row>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
        style=" display: flex; align-items: center; justify-content: center;"
      >
        <el-button
          size="medium"
          type="primary"
          :loading="crud.status.add == 2"
          @click="crud.submitCU()"
        >保 存</el-button>
        <el-button
          size="medium"
          @click="crud.cancelCU"
        >关 闭</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :close-on-click-modal="false"
      title="错误信息"
      :visible.sync="showErrorMessageVisible"
      width="1200px"
      :append-to-body="true"
      top="5vh"
      :before-close="handleClose"
    >
      <codemirror
        ref="codemirror"
        :value="errorMessage"
        :editor-height="500"
      />
    </el-dialog>

    <dev-details-dialog
    ref="detailsReset"
      :task-code="crunTaskCode"
      :dialog-visible="detailsDialogVisible"
      :on-close="() => { detailsDialogVisible = false, $refs.detailsReset.crud.resetQuery(true)}"
    />
    <dev-all-details-dialog
    ref="detailsReset"
      v-if="alldetailsDialogVisible"
      :dialog-visible="alldetailsDialogVisible"
      :on-close="() => { alldetailsDialogVisible = false, $refs.detailsReset.crud.resetQuery(true)}"
    />
    <el-dialog
      width="30%"
      title="表名称详情"
      :visible="libraryTableNameFlag"
      append-to-body
      @close="libraryTableclose"
    >
      <div>
        <codemirror
          ref="codemirror"
          :value="libraryTableName"
          :editor-height="200"
          :read-only="true"
        />
      </div>
      <span
        slot="footer"
        class="dialog-footer"
        style="text-align: center"
      >
        <el-button
          type="primary"
          @click="libraryTableclose"
        >关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import CRUD, {presenter, header, form, crud} from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import pagination from '@crud/Pagination'
import dataImportTaskApi from '@/api/dataTransfer/devDataTransfer/devDataImportTask'
import devDetailsDialog from './devDetailsDialog.vue'
import devAllDetailsDialog from './devAllDetailsDialog.vue'
import codemirror from '@/components/codemirror/codemirror'
import devDataExportTaskApi from '@/api/dataTransfer/devDataTransfer/devDataExportTask'
import devDataImportListApi from '@/api/dataTransfer/devDataTransfer/devDataImportList'

// crud交由presenter持有
const defaultCrud = CRUD({
  title: '',
  url: '/api/dev/data/import/task/page',
  crudMethod: {...dataImportTaskApi}
})
const defaultForm = {
  filePath: null
}

export default {
  name: 'ScriptCheckResult',
  components: {rrOperation, pagination, devDetailsDialog, codemirror, devAllDetailsDialog},
  mixins: [presenter(defaultCrud), header(), crud(), form(defaultForm)],
  data() {
    return {
      libraryTableName: '',
      libraryTableNameFlag: false,
      load: false,
      detailsDialogVisible: false,
      alldetailsDialogVisible: false,
      showErrorMessageVisible: false,
      errorMessage: null,
      crunTaskCode: null,
      taskStatusList: [
        {label: '构建中', value: 'build'},
        {label: '执行中', value: 'running'},
        {label: '暂停', value: 'suspend'},
        {label: '完成', value: 'finish'},
        {label: '构建失败', value: 'fail'}
      ],
      rules: {
        filePath: [
          {required: true, message: '请输入数据文件时间标识', trigger: 'blur'}
        ]
      }
    }
  },
  created() {
  },
  methods: {
    toShowDetail(taskCode) {
      this.detailsDialogVisible = true
      this.crunTaskCode = taskCode
    },
    toShowAllDetail() {
      this.alldetailsDialogVisible = true
    },
    toShowErrorMessage(row) {
      this.showErrorMessageVisible = true
      if (row.errorMessage !== undefined && row.errorMessage !== null && row.errorMessage !== '') {
        this.errorMessage = row.errorMessage
      } else {
        this.errorMessage = '--无任务错误信息--'
      }
    },
    handleClose() {
      this.showErrorMessageVisible = false
    },
    continueRun(id) {
      this.$confirm(`确定要将该任务下的导出清单重新加载执行吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        dataImportTaskApi.continueRunById(id).then(res => {
          loading.close()
          this.$notify({title: '成功', message: '操作成功！', type: 'success'})
          this.crud.toQuery()
        })
      }).catch(() => {
        loading.close()
      })
    },
    suspend(datas) {
      this.$confirm(`确定要暂停选择的任务吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        dataImportTaskApi.suspend(this.getIds(datas)).then(res => {
          loading.close()
          this.$notify({title: '成功', message: '暂停成功！', type: 'success'})
          this.crud.toQuery()
        })
      }).catch(() => {
        loading.close()
      })
    },
    libraryTableopen(taskCode) {
      this.libraryTableNameFlag = true
      this.libraryTableName = ''
      const params = {
        taskCode: taskCode
      }
      devDataImportListApi.page(params).then(res => {
        const list = res.content
        for (let i = 0; i < list.length; i++) {
          this.libraryTableName += list[i].dbName + '.' + list[i].tableName + '\n'
        }
      })
    },
    libraryTableclose() {
      this.libraryTableNameFlag = false
    },
    restart(datas) {
      this.$confirm(`确定要重启选择的暂停任务吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        dataImportTaskApi.restart(this.getIds(datas)).then(res => {
          loading.close()
          this.$notify({title: '成功', message: '重启成功！', type: 'success'})
          this.crud.toQuery()
        })
      }).catch(() => {
        loading.close()
      })
    },
    abolish(datas) {
      this.$confirm(`确定要中止选择的任务吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        dataImportTaskApi.abolish(this.getIds(datas)).then(res => {
          loading.close()
          this.$notify({title: '成功', message: '中止成功！', type: 'success'})
          this.crud.toQuery()
        })
      }).catch(() => {
        loading.close()
      })
    },
    dynamicSuspendButton(datas) {
      const status = this.getStatus(datas)
      return !status.every(item => item === 'running') || datas.length === 0
    },
    dynamicRestartButton(datas) {
      const status = this.getStatus(datas)
      return !status.every(item => item === 'suspend') || datas.length === 0
    },
    dynamicAbolishButton(datas) {
      const status = this.getStatus(datas)
      return !status.every(item => item === 'suspend' || item === 'running') || datas.length === 0
    },
    getIds(data) {
      const ids = []
      if (data instanceof Array) {
        data.forEach(val => {
          ids.push(val.id)
        })
      } else {
        ids.push(data.id)
      }
      return ids
    },
    getStatus(data) {
      const status = []
      if (data instanceof Array) {
        data.forEach(val => {
          status.push(val.taskStatus)
        })
      } else {
        status.push(data.taskStatus)
      }
      return status
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
/deep/ .el-upload-dragger {
  width: 300px !important;
  height: 150px !important;
}

.iconSize {
  border: none;
  font-size: 100px;
}
</style>
